<template>
  <div>
    <div class="myCenter center">
      <el-image v-once
                :src="require('@/assets/file/classRoom.jpg')"
                fit="cover"
                lazy
                style="position: absolute;     width: 100%;
    height: 100%;">
      </el-image>
      <div id="login">
        <div id="contain">
          <div id="left_card">
            <div v-if="isSigning" >
              <ImageUpload ref="avatarImage" :limit="1" @update-file-list="handleChangeAvatar"></ImageUpload>
            </div>
            <h1>课程管理系统</h1>
            <span>Welcome to Course Management System</span>
            <button v-if="!isSigning" class="button_cs" @click="startSigning">注册</button>
            <button v-if="isSigning" class="button_cs" @click="startLogin">登录</button>
          </div>
          <div id="right_card">
            <el-card v-if="!isSigning" class="el-card">
              <h2>欢迎登录</h2>
              <el-form ref="userLoginForm" :model="userLoginForm" :rules="rules" class="toLogin">
                <el-form-item prop="username">
                  <el-input v-model="userLoginForm.username" :placeholder="usPlaceholder" type="text"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="userLoginForm.password" placeholder="请输入密码" type="password"></el-input>
                </el-form-item>
              </el-form>
              <div class="remember">
                <el-radio-group v-model="userLoginForm.role">
                  <el-radio :label="1" class="radio" style="margin-left: 12px">学生</el-radio>
                  <el-radio :label="2" class="radio">老师</el-radio>
                  <el-radio :label="3" class="radio">教务人员</el-radio>
                </el-radio-group>
              </div>
              <div id="btn">
                <button class="loginBtn" @click="login">登陆</button>
              </div>
            </el-card>
            <div v-if="isSigning">
              <el-form
                ref="registerForm"
                :model="registerForm"
                :rules="rules"
              >
                <el-form-item label="" prop="name"
                >
                  <el-input
                    v-model="registerForm.name"
                    autocomplete="off"
                    placeholder="请输入您的名字"
                    type="text"
                  ></el-input
                  >
                </el-form-item>
                <el-form-item prop="username"
                >
                  <el-input
                    v-model="registerForm.username"
                    :placeholder="rePlaceholder"
                    autocomplete="off"
                    type="text"
                  ></el-input
                  >
                </el-form-item>
                <el-form-item label="" prop="password"
                >
                  <el-input
                    v-model="registerForm.password"
                    autocomplete="off"
                    placeholder="请输入密码"
                    type="password"
                  ></el-input
                  >
                </el-form-item>
                <el-form-item label="" prop="againPassword"
                >
                  <el-input
                    v-model="registerForm.againPassword"
                    autocomplete="off"
                    placeholder="请再次输入密码"
                    type="password"
                  ></el-input
                  >
                </el-form-item>
                <el-form-item label="" prop="grade" v-if="registerForm.role === 1">
                  <el-select v-model="registerForm.grade" placeholder="请选择年级">
                    <el-option label="大一" value="1"></el-option>
                    <el-option label="大二" value="2"></el-option>
                    <el-option label="大三" value="3"></el-option>
                    <el-option label="大四" value="4"></el-option>
                  </el-select>
                </el-form-item>
                <el-radio-group v-model="registerForm.role">
                  <el-radio :label="1" class="radio" style="margin-left: 12px">学生</el-radio>
                  <el-radio :label="2" class="radio">老师</el-radio>
                </el-radio-group>
              </el-form>
              <button class="registerBtn" @click="goRegister">注册</button>
            </div>
          </div>
        </div>
      </div>
      <el-dialog
        :visible.sync="showEmailVerificationDialog"
        title="邮箱验证"
      >
        <el-form>
          <el-form-item label="邮箱">
            <el-input v-model="registerForm.email" placeholder="请输入您的邮箱"></el-input>
          </el-form-item>
          <el-form-item label="验证码">
            <el-input v-model="registerForm.code" placeholder="请输入验证码"></el-input>
            <el-button @click="sendCode">发送验证码</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="register">继续注册</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {toLogin, register, sendCode} from "@/apis/user";
import ImageUpload from "@/common/ImageUpload.vue";
import common from "@/utils/common";

export default {
  components: {ImageUpload},
  name: "appLogin",
  data() {
    //用户的账号密码校验规则
    const validateUserName = (rule, value, callback) => {
      const pattern = /^[a-zA-Z0-9]+$/; // 正则表达式模式,账号只能为英文或数字
      if (value === "") {
        callback(new Error("账号不能为空"));
      } else if (pattern.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的用户名！！"));
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度错误"));
      } else {
        callback();
      }
    };
    const validatePassWordAgain = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const validateGrade = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入您的所在年级"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入您的姓名"));
      } else {
        callback();
      }
    };
    return {
      showEmailVerificationDialog: false,
      isSigning: false,
      userLoginForm: {
        username: "",
        password: "",
        role: 1
      },
      registerForm: {
        username: "",// 学号，教工号
        password: "",// 密码
        role: 1, // 1为学生，2为老师
        name: "", // 姓名
        grade: "", // 所在年级
        avatarUrl: "",  // 头像
        email: "",
        code: ""
      },
      rules: {
        againPassword: [
          {
            required: true,
            validator: validatePassWordAgain,
            trigger: "blur",
          },
        ],
        username: [
          {
            validator: validateUserName,
            trigger: "blur",
          },
        ],
        password: [
          {
            validator: validatePassword,
            trigger: "blur",
            //指定了触发验证的事件。在这里，"blur" 事件触发了验证，这意味着当用户在输入字段后进行模糊（失去焦点）操作时，将触发验证。
          },
        ],
        name: [
          {
            validator: validateName,
            trigger: "blur",
          }
        ],
        grade: []
      },
      // 默认校验规则，之后可以根据角色动态添加
      defaultRules: {
        grade: [
          {required: true, validator: validateGrade, trigger: "blur"},
        ],
      },
    }
  },
  methods: {
    sendCode(){
      sendCode(this.registerForm.email).then(res=>{
        if (res.data.code === 1){
          this.$message({
            message: "验证码发送成功",
            type: "success",
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
          });
        }
      })
    },
    goRegister(){
      this.$refs.registerForm.validate((valid) => {
        if(valid){
          this.showEmailVerificationDialog = true;
        }
      })
    },
    handleChangeAvatar(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.registerForm.avatarUrl = file.url;
      });
    },
    startSigning() {
      this.isSigning = true;
    },
    startLogin() {
      this.isSigning = false;
    },
    login() {
      this.$refs.userLoginForm.validate((valid) => {
        if (valid) {
          let loginForm = {
            username: this.userLoginForm.username.trim(),
            password: this.$common.encrypt(this.userLoginForm.password.trim()),
            role: this.userLoginForm.role
          }
          toLogin(loginForm).then(res => {
            if (res.data.code === 1) {
              this.$store.commit("loadRole", loginForm.role)
              this.$store.commit("loadCurrentUser", res.data.data);
              this.$store.commit("setJwtToken", res.data.data.jwtToken);
              this.$message({
                message: "登录成功",
                type: "success",
              });
              if (loginForm.role === 3) {
                this.$router.push("/admin");
              } else if (loginForm.role === 1){
                this.$router.push("/course");
              } else {
                this.$router.push("/course-manage-teacher");
              }
            } else {
              this.$message({
                message: res.data.msg,
                type: "error",
              });
            }
          })
        }
      })
    },
    register() {
      //注册方法
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          if (common.isEmpty(this.registerForm.avatarUrl)){
            this.registerForm.avatarUrl = null;
          }
          let data = {
            name: this.registerForm.name,
            username: this.registerForm.username,
            password: this.$common.encrypt(this.registerForm.password),
            role: this.registerForm.role,
            avatarUrl: this.registerForm.avatarUrl,
            grade: this.registerForm.grade,
            emailAddress: this.registerForm.email,
            code: this.registerForm.code
          }
          register(data).then(res => {
            if (res.data.code === 1) {
              this.$message({
                message: "注册申请已提交，等待审核！",
                type: "success",
              });
              this.showEmailVerificationDialog = false;
              // 重置注册表单
              this.$refs.registerForm.resetFields();
            } else {
              this.$message({
                message: res.data.msg,
                type: "error",
              });
            }
          })
        }
      })
    }
  },
  computed: {
    // 计算属性根据role的值动态返回不同的placeholder文本
    usPlaceholder() {
      switch (this.userLoginForm.role) {
        case 1:
          return "请输入学号";
        case 2:
          return "请输入教工号";
        default:
          return "请输入账号";
      }
    },
    rePlaceholder() {
      switch (this.registerForm.role) {
        case 1:
          return "请输入学号";
        case 2:
          return "请输入教工号";
        default:
          return "请输入账号";
      }
    }
  },
  watch: {
    // 观察registerForm.role的变化
    "registerForm.role"(newValue) {
      if (newValue === 1) { // 如果角色为学生
        this.rules.grade = this.defaultRules.grade;
      } else {
        this.rules.grade = []; // 如果角色不是学生，移除年级的校验规则
      }
    },
  }
}
</script>

<style scoped>
@keyframes animate {
  0% {
    filter: hue-rotate(0deg);
  }
  100% {
    filter: hue-rotate(360deg);
  }
}

.registerBtn {
  background-color: #29eac4;
  border: none;
  width: 180px;
  height: 40px;
  border-radius: 50px;
  font-size: 15px;
  color: #fff;
  text-align: center;
  line-height: 40px;
  margin-top: 30px;
}

.button_cs {
  width: 180px;
  height: 40px;
  border-radius: 50px;
  border: 1px solid #fff;
  color: #fff;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
  margin-top: 40px;
  background: rgba(255, 255, 255, 0);
}


.myCenter {
  display: flex;
  justify-content: center;
  align-items: center;
}

.center {
  height: 100vh;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

#login {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-size: 100% 100%;

  #contain {
    height: 45%;
    min-height: 450px;
    width: 48%;
    min-width: 700px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 25px;
    border: 1px solid black;
    background-color: rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(5px);
    box-shadow: -5px -5px 10px rgb(39, 65, 65),
    5px 5px 20px aqua;
    /* 5秒 infinite循环播放无限次 linear匀速  */
    animation: animate 5s linear infinite;
    display: flex;
    flex-direction: row;
    text-align: center;
    align-items: center;

    #left_card {
      width: 50%;

      h1 {
        color: white;
        white-space: nowrap;
      }

      span {
        font-size: 1.2rem;
        text-align: center;
        color: white;
        white-space: nowrap;
      }
    }

    #right_card {
      width: 50%;
      display: flex;
      justify-content: center;
      align-items: center;

      .el-card {
        margin: 0 45px;
        border-radius: 25px;
        background-color: rgba(255, 255, 255, 0.1);
      }

      h2 {
        margin-bottom: 5px;
      }

      .toLogin {
        input {
          width: 80%;
          height: 45px;
          margin-top: 10px;
          border: 1px solid white;
          background-color: rgba(255, 255, 255, 0.5);
          border-radius: 10px;
          font-size: inherit;
          padding-left: 20px;
          outline: none;
        }
      }

      .remember {
        text-align: center; /* 文本居中对齐 */
        font-size: 1rem; /* 字体大小设置为1rem */
        position: relative; /* 设置相对定位，作为子元素绝对定位的参考 */
        margin-top: 7px;
      }

      .radio {
        color: black;
        width: 15%;
        margin-left: 20px
      }

      .loginBtn {
        width: 30%;
        height: 35px;
        margin-top: 10px;
        border-radius: 10px;
        background-color: rgba(207, 38, 38, 0.8);
      }

    }
  }
}
</style>
